package com.xiguaji.tiktok.task.aweme.event;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.gugee.tiktok.common.model.dto.SlimBloggerDto;
import com.gugee.tiktok.common.model.spider.aweme.AwemeResponse;
import com.xiguaji.boot.eventbus.Event;
import com.xiguaji.boot.eventbus.EventBusTemplate;
import com.xiguaji.boot.eventbus.IEventListener;
import com.xiguaji.tiktok.task.aweme.spider.AwemeSpiderClient;
import com.xiguaji.tiktok.task.blogger.event.SaveAwemeBloggerEventListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SaveRecommendAwemeEventListener implements IEventListener<SaveRecommendAwemeEventListener.SaveRecommendAwemeEvent> {
    @Autowired
    @Lazy
    EventBusTemplate eventBusTemplate;

    @Autowired
    AwemeSpiderClient awemeSpiderClient;

    @Autowired
    SlimBloggerDto.SlimBloggerDtoMapper slimBloggerDtoMapper;

    @Override
    @Subscribe
    @AllowConcurrentEvents
    public void handle(SaveRecommendAwemeEvent event) {
        AwemeResponse awemeResponse = awemeSpiderClient.get();
        if (awemeResponse == null) return;

        var aweme_list = awemeResponse.getAweme_list();
        if (CollectionUtils.isEmpty(aweme_list)) return;

//        var saveAwemeEvent = new SaveAwemeEventListener.SaveAwemeEvent(event, aweme_list);
//        eventBusTemplate.post(saveAwemeEvent);
        List<SlimBloggerDto> slimBloggerDtos = slimBloggerDtoMapper.mapperAuthor(aweme_list.stream().map(a -> a.getAuthor()).collect(Collectors.toList()));
        var saveAwemeBloggerEvent = new SaveAwemeBloggerEventListener.SaveAwemeBloggerEvent(event, slimBloggerDtos);
        eventBusTemplate.post(saveAwemeBloggerEvent);
    }

    public static class SaveRecommendAwemeEvent extends Event {

        public SaveRecommendAwemeEvent() {
            super("SaveRecommendAweme");
        }
    }
}
